package com.hyhy.hycloud.commons.util;

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * @author lanpengfei
 * @date 2018/12/19
 */
public class ReflectionUtil {

    public static void reflection(Object tar, Object src, Class<?> srcClazz, String fieldName) {
        reflection(tar, src, srcClazz, fieldName, false, false);
    }

    public static void reflection(Object tar, Object src, Class<?> srcClazz, String fieldName, boolean allowNullValue) {
        reflection(tar, src, srcClazz, fieldName, false, false, allowNullValue);
    }

    public static void reflection(Object tar, Object src, Class<?> srcClazz, String fieldName, boolean allowNullField, boolean ignoreNullValue) {
        reflection(tar, src, srcClazz, fieldName, allowNullField, ignoreNullValue, true);
    }

    public static void reflection(Object tar, Object src, Class<?> srcClazz, String fieldName, boolean allowNullField, boolean ignoreNullValue, boolean allowNullValue) {
        Field field = ReflectionUtils.findField(srcClazz, fieldName);
        reflection(tar, src, field, allowNullField, ignoreNullValue, allowNullValue);
    }

    public static void reflection(Object tar, Object src, Field field, boolean allowNullField, boolean ignoreNullValue) {
        reflection(tar, src, field, allowNullField, ignoreNullValue, true);
    }

    public static void reflection(Object tar, Object src, Field field, boolean allowNullField, boolean ignoreNullValue, boolean allowNullValue) {
        Object value = getValue(src, field, allowNullField);
        if (value == null && !allowNullValue) {
            throw new IllegalArgumentException();
        }
        if (value != null || !ignoreNullValue) {
            ReflectionUtils.setField(field, tar, value);
        }
    }

    public static Object getValue(Object src, Class<?> srcClazz, String fieldName, boolean allowNullField) {
        Field field = ReflectionUtils.findField(srcClazz, fieldName);
        return getValue(src, field, allowNullField);
    }

    public static Object getValue(Object src, Field field, boolean allowNullField) {
        if (field != null) {
            ReflectionUtils.makeAccessible(field);
            return ReflectionUtils.getField(field, src);
        } else {
            if (!allowNullField) {
                throw new UnsupportedOperationException(new NoSuchFieldException());
            }
            return null;
        }
    }

}
